<%@ page contentType="text/html;charset=UTF-8"%>
<%@ include file="/common/taglibs.jsp"%>
<!DOCTYPE html>
<html>
<head>
	<title><s:text name="system.index.title"/></title>
	<%@ include file="/common/meta-css.jsp" %>
	<link href="${r"${ctx}"}/js/fullcalendar/core/main.min.css" rel="stylesheet" type="text/css"/>
	<link href="${r"${ctx}"}/js/fullcalendar/daygrid/main.min.css"}/panel.css" rel="stylesheet" type="text/css"/>
	<link href="${r"${ctx}"}/js/fullcalendar/timegrid/main.min.css"}/panel.css" rel="stylesheet" type="text/css"/>
	<#import "common/field.ftl" as fieldftl>
	<#assign entityName=root.entityName />
	<#assign formList=root.dataSource.formList/>
	<#assign titleName=root.moduleProperties.caption/>
	<#assign i18nKey=root.moduleProperties.i18nKey/>
	<#assign moduleKey=root.moduleProperties.key/>

	<#-- 关联表表 -->
	<#assign realEntityName = entityName />
	<#if root.moduleProperties.relevanceModule??>
		<#assign relevanceModule=root.moduleProperties.relevanceModule/>
		<#list formList as form>
			<#if form.isMaster>
				<#assign realEntityName = form.entityName />
				<#break/>
			</#if>
		</#list>
	<#else>
		<#assign relevanceModule=""/>
	</#if>

	<#assign isShowInQueryList=false/><#--标识是否存在列表页面显示的tabs-->
	<#assign flowList= root.flowList />
	<#if formList??>
	<#list formList as form>
	<#if form.isMaster>
	<style type="text/css"><#-- 初始化样式 -->
		<@fieldftl.initQueryPageFormCssOrJavascript formList=formList eventKey="addCssStyle"/>
	</style>
</head>
<body>
<@compress single_line=true>
	<div class="easyui-layout" fit="true" id="layout_body">
		<@fieldftl.initFormTree form=form/>
		<div region="center" title="" border="false">
			<div class="easyui-layout" fit="true">
				<@fieldftl.initFormTabQuery form=form isInitTab=true/>
				<div region="center" title="" border="false" style="padding:2px 8px;">
					<div id="queryListToolBar">
						<@fieldftl.getQueryViewV2 formList=formList />
					</div>
					<div id="queryList"></div>
				</div>
			</div>
		</div>
	</div>
	<div style="display:none;">
		<div id="pl_tt">
			<a href="#" id="a_switch_query" class="icon-menu" title="<s:text name="system.button.switchQueryType.title"/>" style="display:none;"></a>
			<a href="#" id="a_exp_clp" class="accordion-expand" title="<s:text name="system.button.expand.title"/>"></a>
		</div>
	</div>
<#-- 新版easyui在初始化layout时，将会查询children中的form元素，如存在则初始化对form兄弟元素无效 -->
	<div style="display:none;">
		<form method="post" name="hidFrm" id="hidFrm" >
			<textarea style="display:none;" name="hid_queryParams" id="hid_queryParams">${r"${param.queryParams}"}</textarea><#-- 查询参数 -->
			<textarea style="display:none;" name="hid_addParams" id="hid_addParams">${r"${param.addParams}"}</textarea><#-- 新增参数 -->
			<input type="hidden" name="hid_relevanceModule" id="hid_relevanceModule" value="${entityName}"/><#-- 关联模块 -->
		</form>
	</div>
	<div class="container-fluid advance-query-form" style="margin-top:10px;display:none;">
		<div class="row form-group">
			<div class="col-sm-12">
				<div class="input-group input-group-sm">
					<span class="input-group-addon" id="sizing-addon3">自定义查询条件</span>
					<select id="queryFieldSel"></select>
					<span class="input-group-btn">
		        <a href="javascript:;" title="收藏常用查询字段" role="button" class="btn btn-default validInView" type="button" onclick="$ES.doAddAQvToFavorite(function(){alert('常用查询字段已收藏！');})"><span class="glyphicon glyphicon-star-empty" aria-hidden="true"></span></a>
		      </span>
				</div>
			</div>
		</div>
		<form id="queryForm" onsubmit="return false;">
		</form>
	</div>
</@compress>
<%@ include file="/common/meta-js.jsp" %>
<script type="text/javascript" src="${r"${ctx}"}/js/fullcalendar/core/main.min.js"></script>
<script type="text/javascript" src="${r"${ctx}"}/js/fullcalendar/daygrid/main.min.js"></script>
<script type="text/javascript" src="${r"${ctx}"}/js/fullcalendar/timegrid/main.min.js"></script>
<script type="text/javascript" src="${r"${ctx}"}/js/fullcalendar/interaction/main.min.js"></script>
<script type="text/javascript" src="${r"${ctx}"}/js/fullcalendar/core/locales-all.min.js"></script>
<script type="text/javascript">
	var _userList={};

	function getAddParams() {
		var param =$("#hid_addParams").val();
		var qp = $.parseJSON(param);
		return qp;
	}

	function getQueryParams(start, end) {
		var param = $("#simpleQueryForm").serializeArrayToParam();
		$.extend(true, param, $("#queryForm").serializeArrayToParam());
		param["sort"] = <#if ((form.sortName)!"") != "">'${form.sortName}'<#else>'id'</#if>;
		param["order"] = <#if ((form.sortOrder)!"") != "">'${form.sortOrder}'<#else>'desc'</#if>;
		var strParam = JSON.stringify(param);
		var params = [];
		params.push("&queryParams=");
		params.push(encodeURIComponent(strParam));
		var ap = null;
		if($("#_commonTypeTree_div_").length) {
			ap = $("#_commonTypeTree_div_").data("addParam");
		}
		ap = $.extend({}, getAddParams(), ap);
		if(window.fcAddParamFunc) {
			$.extend(ap, window.fcAddParamFunc(start, end));
		}
		params.push("&addParams=");
		params.push(encodeURIComponent(JSON.stringify(ap)));
		return params.join("");
	}

	function getOption() {
		return {
			eventSources:[
				{
					events: function(info, callback, failureCallback) {
						var data = {
							page:1,
							rows:65535
						};
						var qp = $("#queryForm").data("queryParams");
						if(qp) {
							$.extend(true, data, qp);
						}
						if(window.fcQueryParamFunc) {
							$.extend(true, data, window.fcQueryParamFunc(info.start, info.end, info.timeZone));
						}
						<#-- data["filter_GED_" + fcOpt.startDateField] = start.format("YYYY-MM-DD");
                        data["filter_LED_" + fcOpt.endDateField] = end.format("YYYY-MM-DD");-->
						var opt = {
							data:data,
							url:'${r"${ctx}"}/gs/gs-mng!queryList.action?entityName=${form.entityName}',
							success:function(data){
								var events = [];
								if(data.rows) {
									events = data.rows.map(function(event, index) {
										if(window.fcResultFunc) {
											return window.fcResultFunc(event, index);
										} else {
											return event;
										}
									});
								}
								callback(events);
							}
						};
						fnFormAjaxWithJson(opt);
					}
				}
			],
			selectable: true,
			selectHelper:true,
			select:function(info) {
				if(window.doAdd) {
					window.doAdd(info.start, info.end);
				}
			},
			eventClick:function(info) {
				if(window.doDblView) {
					window.doDblView(info.event.id);
				}
			}
			<security:authorize url="/gs/gs-mng!add.action?entityName=${entityName}">
			,customButtons: {
				addButton: {
					text: '<s:text name="system.button.add.title"/>',
					click: function() {
						doAdd();
					}
				}
			},
			header: {
				left: 'prev,next today addButton',
				center: 'title',
				right: 'dayGridMonth,timeGridWeek,timeGridDay'
			}
			</security:authorize>
		};
	}

	<@fieldftl.initFormQueryPageEvent form=form /> <#-- 初始化查询页面事件 -->

	function doResetQuery(isResetAdQuery) {
		!isResetAdQuery && $ES.doResetAdvanceQuery("simpleQueryForm");
		$ES.doResetAdvanceQuery();
		doQuery();
	}

	var _ad_query_opt_ = {"data":<@fieldftl.getQueryViewJson formList=formList/>,"isInit":false,"entityName":"${entityName}"};
	function doAdvanceQuery() {
		openFormWinV2({"message":$(".advance-query-form"),"isIframe":false,"isModal":false,
			"okTitle":"<s:text name="system.search.button.title"/>","cancelTitle":"<s:text name="system.search.reset.title"/>"
			,onAfterSure:function(win) {
				doQuery();
			}, onAfterCancel:function(win) {
				doResetQuery(true);
			}});
		$ES.initAdvanceQuery(_ad_query_opt_);
	}

	//查询
	function doQuery(paramObj, isInit) {
		paramObj = paramObj || {};
		if(window.onBeforeQuery) {
			window.onBeforeQuery(paramObj);
		}
		var param = $("#simpleQueryForm").serializeArrayToParam();
		$.extend(true, param, paramObj);<#-- 简单查询 -->
		if($("#ul_tab_query").length) {
			var obj = $("#ul_tab_query").data("queryParam");
			$.extend(true, param, obj);
		}
		if($("#_commonTypeTree_div_").length) {
			var obj = $("#_commonTypeTree_div_").data("queryParam");
			$.extend(true, param, obj);
		}
		$.extend(true, param, $("#queryForm").serializeArrayToParam());<#-- 高级查询 -->
		var qps = getFormQueryParams();<#-- 加入初始化查询条件 -->
		param = $.extend(true, qps, param);
		$("#queryForm").data("queryParams", param);
		if(isInit) { <#-- 初始化列表 -->
			var opt = getOption();
			initFullCalendar(opt);
		} else {
			doRefreshDataGrid();
		}
	}

	<#--
	/*  日历显示必需函数 */
function fcQueryParamFunc(start, end, timezone) {
     return {
     	"filter_GED_kaishishijian":start.format("YYYY-MM-DD"),
        "filter_LED_jieshushijian":end.format("YYYY-MM-DD")
     }
}

function fcAddParamFunc(start, end) {
     var data = {};
     if(start) {
     	data["kaishishijian"] = start.format("YYYY-MM-DD hh:mm");
     }
     if(end) {
        data["jieshushijian"] = end.format("YYYY-MM-DD hh:mm");
     }
     return data;
}

function fcResultFunc(row, index) {
	return {
    	id: row.id,
		title: row.yuyuebumen + " 预约 " + row.huiyishitext + "【" + row.yuyueren + "】",
		start: row.kaishishijian,
	    end: row.jieshushijian,
		content:row.shiyou
    }
}
	-->

	function initFullCalendar(opt) {
		var defaultOpt = {
			plugins: [ 'interaction', 'dayGrid', 'timeGrid' ],
			header: {
				left: 'prev,next today',
				center: 'title',
				right: 'dayGridMonth,timeGridWeek,timeGridDay'
			},
			defaultDate: $today$,
				<c:if test="${r"${LOCALE == 'zh_CN'}"}">
				locale: 'zh-cn',
				</c:if>
				<c:if test="${r"${LOCALE == 'zh_TW'}"}">
				locale: 'zh-tw',
				</c:if>
			//height:"auto",
			weekNumbers: true,
			navLinks: true,
			editable: true,
			eventLimit: true<#--,
			eventClick: function(event) {
				var el = $(this);
				el.popover({
					title:event.title,
					content: event.content,
					html: true,
					placement: "auto",
					container: 'body',
					trigger: 'hover'
				});
				el.popover('show');
				return false;
			}-->
		};
		var fcOpt = $.extend(true, {}, defaultOpt, opt);
		var calendarEl = document.getElementById('queryList');
		calendar = new FullCalendar.Calendar(calendarEl, fcOpt);
		calendar.render();
	}
	//新增
	function doAdd(start, end) {
		top.addTab('<s:text name="system.button.add.title"/><s:text name="${i18nKey!titleName}"/>', '${r"${ctx}"}/gs/gs-mng!add.action?entityName=${entityName}'+ getQueryParams(start, end));
	}

	//查看tab
	function doDblView(id) {
		top.addTab('<s:text name="system.button.view.title"/><s:text name="${i18nKey!titleName}"/>-'+id, '${r"${ctx}"}/gs/gs-mng!view.action?entityName=${entityName}&id=' + id+ getQueryParams());
	}

	//重定义尺寸
	function doResizeDataGrid() {

	}

	//刷新列表
	function doRefreshDataGrid() {
		if(calendar) calendar.refetchEvents();
	}

	function doRefreshDataGridOnPage() {
		if(calendar) calendar.refetchEvents();
	}

	function initQueryData() {
		<#assign fields=form.fieldList!>
		<#if fields??&&fields?size gt 0>
		<#list fields as field>
		<#if (field.queryProperties.showInSearch)!false || (field.queryProperties.showInCommonSearch)!false>
		<@fieldftl.initControlsData field=field type="listQuery" prefix="query_" entityName=form.entityName
            formKey="" moduleTitle="" isAsync="true"/>
		</#if>
		<#if (field.queryProperties.showInTreeSearch)!false>
		<@fieldftl.initTreeQuery field=field prefix="dg_" entityName=form.entityName/>
		</#if>
		</#list>
		</#if>
		<#-- 初始化子表查询条件 -->
		<#list formList as subForm>
		<#if !subForm.isMaster && !((subForm.isVirtual)!false)>
		<#assign fields=subForm.fieldList!>
		<#if fields??&&fields?size gt 0>
		<#list fields as field>
		<#if (field.queryProperties.showInSearch)!false  || (field.queryProperties.showInCommonSearch)!false>
		<@fieldftl.initControlsData field=field type="listQuery" prefix=("query_"+subForm.key+"_") entityName=subForm.entityName formKey=subForm.key
             moduleTitle="" isAsync="true"/>
		</#if>
		</#list>
		</#if>
		</#if>
		</#list><#-- 系统状态初始化参数 -->
		query_statusJson = $ES.getStatusList();
		initTabControlsShowInList();
	}

	<#-- 初始化显示在列表页面的Tab页内容下包含控件数据 -->
	function initTabControlsShowInList(){
		<#if isShowInQueryList>
		<#list root.dataSource.tabsList as tabs >
		<#list tabs.tabList as tab>
		<#if form.key==tab.form>
		<#if form.isMaster && tab.isShowInQueryList?? && tab.isShowInQueryList><#--主表分tab页面-->
		<#assign fields=form.fieldList!>
		<#if fields??&&fields?size gt 0>
		<#list fields as field>
		<#if field.editProperties.visible && !(field.isCaption?? && field.isCaption)>
		<#if field.tabRows==tab.rows && field.tabCols==tab.cols>
		<@fieldftl.initControlsData field=field type="query" prefix="" entityName=form.entityName formKey="" moduleTitle=i18nKey!titleName />
		<@fieldftl.initFieldEvent field=field/>
		</#if>
		</#if>
		</#list>
		</#if>
		</#if>
		</#if>
		</#list>
		</#list>
		$("#showInQueryList :input").attr({"readonly":"readonly"});
		</#if>
	}

	<#-- 初始化tab查询 -->
	function initTabQuery(tabData, dataParam, fpName, tabKey, tabTitle) {
		if(tabData && tabData.length && dataParam) {
			var dtObj = {};
			dtObj[dataParam.key] = "";
			dtObj[dataParam.caption] = tabTitle + "(全部)";
			var arr = [dtObj];
			tabData = arr.concat(tabData);
			var ulHtmlArr = [];
			var tabKeyId = "ul_tab_query_"+tabKey;
			ulHtmlArr.push(['<div class="btn-toolbar" role="toolbar" id="', tabKeyId,'">'].join(''));
			for(var i=0,len=tabData.length;i<len;i++) {
				var key = tabData[i][dataParam.key];
				var caption = tabData[i][dataParam.caption];
				ulHtmlArr.push('<div class="btn-group btn-group-xs">');
				ulHtmlArr.push('<button type="button" class="btn btn-default navbar-btn');
				if(key !== "") {<#-- 可过滤按钮 -->
					ulHtmlArr.push(' btn-can-click');
				}
				if(i == 0) {
					if(key !== "") {
						ulHtmlArr.push(' btn-success');
					} else {
						ulHtmlArr.push(' btn-primary');
					}
					var paramObj = $("#ul_tab_query").data("queryParam") || {};
					paramObj[fpName] = key;
					$("#ul_tab_query").data("queryParam", paramObj);
				}
				ulHtmlArr.push('" keyVal="');
				ulHtmlArr.push(key);
				ulHtmlArr.push('">');
				ulHtmlArr.push(caption);
				ulHtmlArr.push('</button>');
				ulHtmlArr.push("</div>");
			}
			$("#ul_tab_query").append(ulHtmlArr.join(""));
			$("#"+tabKeyId+" button.btn-can-click").click(function(event) {
				var paramObj = $("#ul_tab_query").data("queryParam") || {};
				var keyVal = "";
				if($(this).hasClass("btn-success")) {
					$(this).removeClass("btn-success");
				} else {
					$(this).addClass("btn-success");
				}
				var valArr = [];
				$("#"+tabKeyId+" button.btn-success").each(function() {
					var val = $(this).attr("keyVal");
					if($.isNumeric(val) || val) {
						valArr.push(val);
					}
				});
				keyVal = valArr.join(",");
				paramObj[fpName] = keyVal;
				$("#ul_tab_query").data("queryParam", paramObj);
				doQuery();
			});
		}
	}

	function initTabQueryExpand() {
		var tbs = $("#ul_tab_query div.btn-toolbar");
		if(tbs.length > 1) {
			var tb = $(tbs.get(0));
			tb.append(['<div class="btn-group btn-group-xs pull-right">',
				'<button type="button" class="btn btn-default navbar-btn btn-expand" title="more shrink/expand">',
				'', '<i class="fa fa-chevron-up"></i>',
				'</button></div>'].join(""));
			tb.find("button.btn-expand").click(function() {
				tb.nextAll().fadeToggle("normal","linear");
				var ti = $(this).find("i");
				ti.toggleClass("fa-chevron-up").toggleClass("fa-chevron-down");
			});
		}
	}

	function getFormQueryParams() {
		var param =$("#hid_queryParams").val();
		var qp = $.parseJSON(param);
		if(qp) {
			for(var k in qp) {
				if(qp[k] === "$curUserId$") {
					qp[k] = $curUserId$;
				} else if(qp[k] === "$curOrgCode$%") {
					qp[k] = $curOrgCode$ + "%";
				} else if(qp[k] === "$curOrgId$") {
					qp[k] = $curOrgId$;
				}
			}
		}
		return qp;
	}

	function initSimpleQuery() {
		<@fieldftl.getQueryViewV2 formList=formList isInitEvent=true />
		<#--$("#simpleQueryForm").on('keypress', 'input.select2-search__field', function(e) {if(e.keyCode==13) {doQuery();return false;}});-->
	}

	$(document).ready(function() {
		initQueryData();

		<@fieldftl.initFormTabQuery form=form isInitTab=false/>

		if($("#_commonTypeTree_div_").length == 0 || !$("#_commonTypeTree_div_").attr("issys")) { <#-- 无系统字典树查询时自动查询，有时，则由字典树触发查询 -->
			doQuery(null, true);
		}
		jwpf.bindHotKeysOnListPage();
	<c:if test="${r"${param.isHideQc=='1'}"}">
				$("#layout_body").layout("collapse", "west");
	</c:if>

		initSimpleQuery();
	});

</script>
<script type="text/javascript">
	<@fieldftl.initQueryPageFormCssOrJavascript formList=formList eventKey="addJavaScript"/>
</script>
<@fieldftl.initQueryPageFormCssOrJavascript formList=formList eventKey="referJsOrCss"/>
</body>
</#if>
</#list>
</#if>
</html>